import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(userid: string, pcpwd: string): Promise<any> {
    const user = await this.usersService.validateUser(userid, pcpwd);
    if (user) {
      const { pcpwd, ...result } = user;
      return result;
    }
    return null;
  }

  async login(user: any) {
    const payload = {
      userid: user.userid,
      sub: user.userid,
      id: user.id,
      mobile: user.mobile,
      admin:user.admin,
      address:user.address
    };
    console.log(payload)
    const options = { expiresIn: '24h' }; // 设置过期时间为24小时

    const token = this.jwtService.sign(payload, options);

    // 获取过期时间
    const decodedToken = this.jwtService.decode(token) as any;
    const token_expired = new Date(decodedToken.exp * 1000);

    // 构建用户信息，包含department字段
    const userInfo = {
      id: user.id,
      userid: user.userid,
      name: user.name,
      department: user.department,
      position: user.position,
      mobile: user.mobile,
      gender: user.gender,
      email: user.email,
      weixinid: user.weixinid,
      avatar: user.avatar,
      admin: user.admin,
      address: user.address,
      status: user.status
    };

    return {
      token,
      token_expired,
      user: userInfo
    };
  }

  async decodeToken(token: string): Promise<any> {
    try {
      const decoded = this.jwtService.verify(token);
      console.log(decoded)

      return decoded; // 假设返回的对象包含 `role` 属性
    } catch (error) {
      return null;
    }
  }

  async findUserById(id: string): Promise<any> {
    return this.usersService.findOneByUserId(id);
  }
}
